package com.zwps.common.core.mybatis.interceptor;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.zwps.common.api.model.vo.LoginInfoVO;
import com.zwps.common.api.model.vo.LoginUserVO;
import com.zwps.common.core.context.LoginInfoContext;
import com.zwps.common.mybatis.plus.interceptor.ValueFillInterceptor;

import cn.hutool.core.date.DateUtil;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

public class UserActionValueFillInterceptor extends ValueFillInterceptor {

    public static final String CREATE_BY = "create_by";
    private static final String CREATE_TIME = "create_time";
    private static final String UPDATE_BY = "update_by";
    private static final String UPDATE_TIME = "update_time";

    private final Function<String, Expression> NOW = (a) -> new StringValue(
            DateUtil.formatLocalDateTime(LocalDateTime.now()));

    private final Function<String, Expression> USER_ID = (a) -> {
        LoginInfoVO loginInfoVO;
        try {
            loginInfoVO = LoginInfoContext.getLoginInfo();
        } catch (Exception e) {
            return null;
        }
        LoginUserVO user = loginInfoVO.getUser();
        if (user != null) {
            return new StringValue(user.getId());
        }
        return null;
    };

    public UserActionValueFillInterceptor(MybatisPlusInterceptor mybatisPlusInterceptor) {
        mybatisPlusInterceptor.addInnerInterceptor(this);
    }

    public String getCreateByField() {
        return CREATE_BY;
    }

    public String getCreateTimeField() {
        return CREATE_TIME;
    }

    public String getUpdateByField() {
        return UPDATE_BY;
    }

    public String getUpdateTimeField() {
        return UPDATE_TIME;
    }

    public void addTableNameToInsertAndUpdate(String tableName) {
        addTableNameToInsert(tableName);
        addTableNameToUpdate(tableName);
    }
    
    public void addTableNameToInsert(String tableName) {
        List<FieldValue> list = new ArrayList<FieldValue>();
        list.add(new FieldValue(getCreateByField(), USER_ID));
        list.add(new FieldValue(getCreateTimeField(), NOW));
        addInsertValueFill(tableName, list);
    }

    public void addTableNameToUpdate(String tableName) {
        List<FieldValue> list = new ArrayList<FieldValue>();
        list.add(new FieldValue(getUpdateByField(), USER_ID));
        list.add(new FieldValue(getUpdateTimeField(), NOW));
        addUpdateValueFill(tableName, list);
    }

}
